//
//  FCCMessageManager.swift
//  chatUIDemo
//
//  Created by admin on 2025/7/10.
//

import UIKit
import Foundation

// MARK: - 消息管理器协议
protocol FCCMessageManagerDelegate: AnyObject {
    func qfcMessageManager(_ qfcManager: FCCMessageManager, didReceiveMessage qfcMessage: FCCMessage)
    func qfcMessageManager(_ qfcManager: FCCMessageManager, didUpdateMessage qfcMessage: FCCMessage)
    func qfcMessageManager(_ qfcManager: FCCMessageManager, didFailToSendMessage qfcMessage: FCCMessage, error: Error)
}

// MARK: - 消息管理器
class FCCMessageManager {
    
    // MARK: - 属性
    weak var qfcDelegate: FCCMessageManagerDelegate?
    private var qfcMessages: [FCCMessage] = []
    private let qfcCurrentUserId: String
    
    // MARK: - 初始化
    init(qfcCurrentUserId: String) {
        self.qfcCurrentUserId = qfcCurrentUserId
    }
    
    // MARK: - 公共方法
    func qfcGetAllMessages() -> [FCCMessage] {
        return qfcMessages
    }
    
    func qfcAddMessage(_ qfcMessage: FCCMessage) {
        qfcMessages.append(qfcMessage)
        qfcDelegate?.qfcMessageManager(self, didReceiveMessage: qfcMessage)
    }
    
    func qfcSendTextMessage(_ qfcContent: String) {
        let qfcMessage = FCCTextMessage(
            qfcContent: qfcContent,
            qfcSenderId: qfcCurrentUserId,
            qfcIsOutgoing: true,
            qfcStatus: .qfcSending
        )
        
        qfcAddMessage(qfcMessage)
        qfcSimulateSendingProcess(qfcMessage)
    }
    
    func qfcSendImageMessage(_ qfcImage: UIImage) {
        let qfcMessage = FCCImageMessage(
            qfcImage: qfcImage,
            qfcSenderId: qfcCurrentUserId,
            qfcIsOutgoing: true,
            qfcStatus: .qfcSending
        )
        
        qfcAddMessage(qfcMessage)
        qfcSimulateSendingProcess(qfcMessage)
    }
    
    func qfcSendAudioMessage(qfcDuration: Int) {
        let qfcMessage = FCCAudioMessage(
            qfcDuration: qfcDuration,
            qfcSenderId: qfcCurrentUserId,
            qfcIsOutgoing: true,
            qfcStatus: .qfcSending
        )
        
        qfcAddMessage(qfcMessage)
        qfcSimulateSendingProcess(qfcMessage)
    }
    
    func qfcUpdateMessageStatus(_ qfcMessageId: String, qfcStatus: FCCMessageStatus) {
        guard let qfcMessage = qfcMessages.first(where: { $0.qfcId == qfcMessageId }) else {
            return
        }
        
        qfcMessage.qfcStatus = qfcStatus
        qfcDelegate?.qfcMessageManager(self, didUpdateMessage: qfcMessage)
    }
    
    func qfcDeleteMessage(_ qfcMessageId: String) {
        qfcMessages.removeAll { $0.qfcId == qfcMessageId }
    }
    
    func qfcResendMessage(_ qfcMessageId: String) {
        guard let qfcMessage = qfcMessages.first(where: { $0.qfcId == qfcMessageId }) else {
            return
        }
        
        qfcMessage.qfcStatus = .qfcSending
        qfcDelegate?.qfcMessageManager(self, didUpdateMessage: qfcMessage)
        qfcSimulateSendingProcess(qfcMessage)
    }
    
    // MARK: - 私有方法
    private func qfcSimulateSendingProcess(_ qfcMessage: FCCMessage) {
        // 模拟网络请求发送消息
        DispatchQueue.global().asyncAfter(deadline: .now() + Double.random(in: 1.0...3.0)) {
            let qfcSuccess = Bool.random() // 模拟成功/失败
            
            DispatchQueue.main.async {
                if qfcSuccess {
                    qfcMessage.qfcStatus = .qfcSent
                    self.qfcDelegate?.qfcMessageManager(self, didUpdateMessage: qfcMessage)
                } else {
                    qfcMessage.qfcStatus = .qfcFailed
                    let qfcError = NSError(domain: "FCCMessageError", code: 1001, userInfo: [NSLocalizedDescriptionKey: "Failed to send"])
                    self.qfcDelegate?.qfcMessageManager(self, didFailToSendMessage: qfcMessage, error: qfcError)
                }
            }
        }
    }
    
    // MARK: - 模拟接收消息
    func qfcSimulateReceiveMessage() {
        let qfcRandomMessages = [
            "Hello!",
            "Nice weather today",
            "What are you doing?",
            "Let's have dinner tonight",
            "Sure, no problem",
            "Thank you for your help",
            "See you tomorrow!"
        ]
        
        let qfcRandomContent = qfcRandomMessages.randomElement() ?? "Hello"
        let qfcMessage = FCCTextMessage(
            qfcContent: qfcRandomContent,
            qfcSenderId: "other_user",
            qfcIsOutgoing: false,
            qfcStatus: .qfcSent
        )
        
        qfcAddMessage(qfcMessage)
    }
    
    // MARK: - 加载历史消息
    func qfcLoadHistoryMessages() {
        let qfcHistoryMessages: [FCCMessage] = [
            FCCTextMessage(
                qfcContent: "Welcome to the Chat App!",
                qfcSenderId: "system",
                qfcIsOutgoing: false,
                qfcTimestamp: Date(timeIntervalSinceNow: -86400), // 1天前
                qfcStatus: .qfcSent
            ),
            FCCTextMessage(
                qfcContent: "Hello, nice to meet you",
                qfcSenderId: "other_user",
                qfcIsOutgoing: false,
                qfcTimestamp: Date(timeIntervalSinceNow: -7200), // 2小时前
                qfcStatus: .qfcSent
            ),
            FCCTextMessage(
                qfcContent: "Nice to meet you too!",
                qfcSenderId: qfcCurrentUserId,
                qfcIsOutgoing: true,
                qfcTimestamp: Date(timeIntervalSinceNow: -7100),
                qfcStatus: .qfcSent
            ),
            FCCImageMessage(
                qfcImage: UIImage(systemName: "photo.artframe"),
                qfcSenderId: "other_user",
                qfcIsOutgoing: false,
                qfcTimestamp: Date(timeIntervalSinceNow: -3600), // 1小时前
                qfcStatus: .qfcSent
            ),
            FCCAudioMessage(
                qfcDuration: 25,
                qfcSenderId: qfcCurrentUserId,
                qfcIsOutgoing: true,
                qfcTimestamp: Date(timeIntervalSinceNow: -1800), // 30分钟前
                qfcStatus: .qfcSent
            )
        ]
        
        qfcMessages = qfcHistoryMessages
    }
}

// MARK: - 消息操作扩展
extension FCCMessageManager {
    
    // 复制消息内容
    func qfcCopyMessage(_ qfcMessageId: String) {
        guard let qfcMessage = qfcMessages.first(where: { $0.qfcId == qfcMessageId }) else {
            return
        }
        
        var qfcContentToCopy = ""
        
        switch qfcMessage.qfcType {
        case .qfcText:
            if let qfcTextMessage = qfcMessage as? FCCTextMessage {
                qfcContentToCopy = qfcTextMessage.qfcContent
            }
        case .qfcImage:
            qfcContentToCopy = "[Image]"
        case .qfcAudio:
            if let qfcAudioMessage = qfcMessage as? FCCAudioMessage {
                qfcContentToCopy = "[Voice \(qfcAudioMessage.qfcDuration)s]"
            }
        }
        
        UIPasteboard.general.string = qfcContentToCopy
    }
    
    // 转发消息
    func qfcForwardMessage(_ qfcMessageId: String) {
        guard let qfcMessage = qfcMessages.first(where: { $0.qfcId == qfcMessageId }) else {
            return
        }
        
        // 创建新的消息对象用于转发
        var qfcForwardedMessage: FCCMessage
        
        switch qfcMessage.qfcType {
        case .qfcText:
            let qfcOriginalMessage = qfcMessage as! FCCTextMessage
            qfcForwardedMessage = FCCTextMessage(
                qfcContent: qfcOriginalMessage.qfcContent,
                qfcSenderId: qfcCurrentUserId,
                qfcIsOutgoing: true,
                qfcStatus: .qfcSending
            )
            
        case .qfcImage:
            let qfcOriginalMessage = qfcMessage as! FCCImageMessage
            qfcForwardedMessage = FCCImageMessage(
                qfcImage: qfcOriginalMessage.qfcImage,
                qfcSenderId: qfcCurrentUserId,
                qfcIsOutgoing: true,
                qfcStatus: .qfcSending
            )
            
        case .qfcAudio:
            let qfcOriginalMessage = qfcMessage as! FCCAudioMessage
            qfcForwardedMessage = FCCAudioMessage(
                qfcDuration: qfcOriginalMessage.qfcDuration,
                qfcSenderId: qfcCurrentUserId,
                qfcIsOutgoing: true,
                qfcStatus: .qfcSending
            )
        }
        
        qfcAddMessage(qfcForwardedMessage)
        qfcSimulateSendingProcess(qfcForwardedMessage)
    }
}